const express = require('express')
const novelsRouter = require('./routes/novels')

const app = express()
app.use(express.json())
app.use('/api/novels', novelsRouter)

async function testAPI () {
  try {
    // 模拟请求对象
    const mockReq = (query = {}, params = {}) => ({
      query,
      params
    })

    const mockRes = () => {
      const res = {}
      res.status = code => {
        res.statusCode = code
        return res
      }
      res.json = data => {
        console.log('Response:', JSON.stringify(data, null, 2))
        return res
      }
      return res
    }

    console.log('=== 测试获取小说列表 ===')
    const novelsHandler = require('./routes/novels')

    // 直接测试数据库查询
    const db = require('./config/database')

    console.log('\n1. 测试基本查询...')
    const novels = await db.query(`
      SELECT * FROM novels 
      WHERE status IN ('ongoing', 'completed', 'suspended')
      ORDER BY updated_at DESC
      LIMIT 5
    `)

    console.log(`找到 ${novels.length} 本小说:`)
    novels.forEach(novel => {
      console.log(`- ${novel.title} (${novel.author}) - 状态: ${novel.status}`)
    })

    console.log('\n2. 测试推荐查询...')
    const recommendations = await db.query(`
      SELECT * FROM novels
      WHERE status IN ('ongoing', 'completed')
      ORDER BY (rating * 0.4 + view_count * 0.0001 * 0.6) DESC
      LIMIT 3
    `)

    console.log(`推荐小说 ${recommendations.length} 本:`)
    recommendations.forEach(novel => {
      console.log(
        `- ${novel.title} (评分: ${novel.rating}, 浏览: ${novel.view_count})`
      )
    })
  } catch (error) {
    console.error('测试失败:', error)
  } finally {
    process.exit(0)
  }
}

testAPI()
